package com.zkt.recommend.application.mq;

import com.zkt.recommend.domain.algorithm.HotQuestionCalculator;
import com.zkt.recommend.domain.algorithm.UserPortraitCalculator;
import com.zkt.recommend.infra.entity.SubjectUserRecord;
import com.zkt.recommend.infra.basic.entity.RecommendUserPortrait;
import com.zkt.recommend.infra.basic.service.IRecommendUserPortraitService;
import com.zkt.recommend.infra.entity.SubjectLabelInfo;
import com.zkt.recommend.infra.rpc.SubjectRPC;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 赵开泰
 * @program jc-club
 * @date 2025/3/25
 * @description
 **/

@Component
@RocketMQMessageListener(topic = "deal-new-question", consumerGroup = "consumer-question")
@Slf4j
public class DealNewQuestion implements RocketMQListener<SubjectUserRecord> {
	
	@Resource
	private HotQuestionCalculator hotQuestionCalculator;
	
	@Resource
	private UserPortraitCalculator userPortraitCalculator;
	
	@Resource
	private IRecommendUserPortraitService recommendUserPortraitService;
	
	@Resource
	private SubjectRPC subjectRPC;
	
	@Override
	public void onMessage(SubjectUserRecord message) {
		if (log.isInfoEnabled()) {
			log.info("处理做题记录：{}", message.toString());
		}
		
		// 更新题目热度
		hotQuestionCalculator.updateQuestionHotScore(message);
		
		// 更新用户画像
		List<Long> userLabels = subjectRPC.getUserLabels(null)
				.stream()
				.map(SubjectLabelInfo::getId)
				.toList();
		
		if (userLabels.contains(message.getLabelId())) {
			RecommendUserPortrait recommendUserPortrait = recommendUserPortraitService.lambdaQuery()
					.eq(RecommendUserPortrait::getUserId, message.getUserId())
					.eq(RecommendUserPortrait::getLabelId, message.getLabelId())
					.list()
					.stream()
					.findFirst()
					.orElse(null);
			
			RecommendUserPortrait newRecommendUserPortrait = userPortraitCalculator.updateUserPortrait(message, recommendUserPortrait);
			
			recommendUserPortraitService.saveOrUpdate(newRecommendUserPortrait);
		}
	}
}
